import React from 'react';
import './roleManage.less';
import {browserHistory} from 'react-router';
import { Input, Button, Table, Modal, Pagination, message } from 'antd';
import config from '../../../config/config';
import $ from 'jquery';
const token = sessionStorage.getItem('token');
const allRouter=config.router;
export default class RoleManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false, //新增角色对话框
            modalType: 'add', //模态框状态 add新增，edit编辑
            Inkey: '',// 关键字
            rolesList: [],// 会员列表
            allList:[],
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            role: {}, //操作的角色数据
            editName: "", //编辑角色的新名称
            addName: "", //新增角色的名称
            tips:'',//提示信息
            tips1:'',//提示信息

        }
    }
    componentDidMount() {
        //获取角色列表
        this.getRolesList();
    }
    //获取角色列表
    getRolesList() {
        let url=allRouter.patientOrigin+'/role/list';
        if(!this.state.Inkey){

            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:res=>{
                    console.log(res);
                    const rolesList = res.roles;
                    if (rolesList.length > 0) {
                        rolesList.forEach((ele, i) => {
                            ele.index = i + 1;
                        });
                    }
                    let allList = [];
                    if(!this.state.Inkey){
                        allList = rolesList;
                    }
                    this.setState({
                        rolesList,
                        allList,
                        rolesCount: res.roles.count,
                    });
                },
                error:err=>{
                    message.config({ top: 80, });
                    message.error('获取角色列表失败，请返回重新操作', 2);
                }
            });
        }
    }
    //分页
    changePage(pageindex) {
        console.log(pageindex);
        this.setState({
            pageindex
        });
    }

    //删除角色
    deleteRole(record) {
        let confirmString=<span></span>;
        //获取该科室下有没有关联医生
        let url=allRouter.patientOrigin+'/role/istThere';
        $.ajax({
            url:url,
            type:'GET',
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                rooid:record._id,
            },
            success:data=>{
                console.log(data);
                if(data.code===200){
                    confirmString=<span>确认删除该角色吗?</span>;
                    Modal.confirm({
                        title: '删除角色',
                        content: confirmString,
                        onCancel: () => { },
                        onOk: () => {
                            let url=allRouter.patientOrigin+'/role/delete';
                            $.ajax({
                                url:url,
                                type: "POST",
                                async: true,
                                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                                data:{
                                    id:record._id,
                                },
                                success:data=>{
                                    if(data.code===200){
                                        message.success('删除角色成功！', 2);
                                        this.getRolesList();
                                    }else{
                                        message.error('删除角色失败，请重新尝试', 2);
                                    }
                                },
                                error:err=>{
                                    console.log(err);
                                }
                            });
                        }
                    })
                }else if(data.code===201){
                    confirmString=<span style={{color:'red'}}>该角色已关联员工，请先解除或更换关联关系</span>;
                    Modal.info({
                        title: '删除角色',
                        content: confirmString,
                        onOk: () => {}
                    })
                }else{
                    message.info("删除角色出错，请重新操作。",1);
                }
            },
            error:err=>{ console.log(err);}
        });


        // Modal.confirm({
        //     title: '删除角色',
        //     content: '谨慎操作！若成功删除，与该角色关联的员工不得登入该后台！！',
        //     cancelText:'取消',
        //     className:'confirm-error',
        //     okText:'确定',
        //     onCancel: () => { },
        //     onOk: () => {
        //         let url=allRouter.patientOrigin+'/role/delete';
        //         $.ajax({
        //             url:url,
        //             type: "POST",
        //             async: true,
        //             headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
        //             data:{
        //                 id:record._id,
        //             },
        //             success:data=>{
        //                 if(data.code===200){
        //                     message.success('删除角色成功！', 2);
        //                     this.getRolesList();
        //                 }else{
        //                     message.error('删除角色失败，请重新尝试', 2);
        //                 }
        //             },
        //             error:err=>{
        //                 console.log(err);
        //             }
        //         });
        //     }
        // })
    }
    //编辑角色名称
    editRole(role) {
        console.log(role);
        this.setState({
            visible: true,
            modalType:'edit',
            role,
        });
    }
    //输入新角色名称
    editRoleName(e) {
        this.setState({
            editName: e.target.value,
        });
        if(/^([\u4e00-\u9fa5]){1,10}$/.test(e.target.value)){
            this.setState({
                tips:'',
            })
        }else{
            this.setState({
                tips:'请输入10字以内中文',
            })
        }
    }

    //添加角色
    addRole() {
        this.setState({
            visible: true,
            modalType: 'add',
        });
    }
    //输入角色名称
    addRoleName(e) {
        this.setState({
            addName: e.target.value,
        });
        if(/^([\u4e00-\u9fa5]){1,10}$/.test(e.target.value)){
            this.setState({
                tips1:'',
            })
        }else{
            this.setState({
                tips1:'请输入10字以内中文',
            })
        }
    }
    //确定添加角色或编辑角色
    handleOk() {
        const { role, editName, addName } = this.state;
        if (this.state.modalType == 'add') {
            if (addName == "") {
                message.error('角色名不能为空，请填写！', 2);
            } else {
               // console.log(addName);
                if(this.state.tips1){
                    return;
                }
                let url=allRouter.patientOrigin+'/role/save';

                $.ajax({
                    url:url,
                    type: "POST",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        name:addName,
                        state:'启用'
                    },
                    success:data=>{
                        if(data.code===200){
                            message.info('角色添加成功');
                            this.getRolesList();
                            this.setState({
                                visible: false,
                                addName: "",
                            });
                        }else if(data.code===201){
                            message.error('角色名称已存在，请修改');
                        }else{
                            message.info('角色名称增加失败');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
            }
        } else {
            if (editName == "") {
                message.error('角色名不能为空，请填写！', 2);
            } else {
                if(this.state.tips){
                    return;
                }
                let url=allRouter.patientOrigin+'/role/update';
               // console.log(editName);
              // console.log(role._id);
                $.ajax({
                    url:url,
                    type: "POST",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        name:editName,
                        id:role._id,
                    },
                    success:data=>{
                        console.log(data);
                        if(data.code===200){
                            message.info('角色修改成功');
                            this.getRolesList();
                            this.setState({
                                visible: false,
                                editName: "",
                            });
                        }else if(data.code===201){
                            message.error('角色名称已存在，请修改');
                        }else{
                            message.info('角色名称增加失败');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
            }
        }
    }
    //取消添加角色
    handleCancel() {
        this.setState({
            visible: false,
            addName: '',
            editName:'',
        });
    }
    //更改角色状态
    changeRoleState(record){
        let that=this;
        //实际更改状态
        let actualEditState=()=>{
            let url=allRouter.patientOrigin+'/role/update';
            $.ajax({
                url:url,
                type: "POST",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                data:{
                    id:record._id,
                    state:currentState,
                },
                success:data=>{
                    console.log(data);
                    if(data.code===200){
                        that.getRolesList();
                    }else{
                        message.info('更改状态错误');
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        };
        let currentState=record.state;
        if(currentState==="启用"){
            currentState="禁用";
            Modal.confirm({
                title: '禁用角色',
                className:'confirm-error',
                content: '谨慎操作！若成功禁用，与该角色关联的员工不得登入该后台！！',
                onCancel: () => { },
                onOk: () => {
                    actualEditState();
                }
            })
        }else if(currentState==="禁用"){
            currentState="启用";
            actualEditState();
        }
    }
    //权限分配函数
    rolePrivilege(record){
        console.log(record);
        browserHistory.push('rolePrivilegeForm/'+record._id+'/'+record.name);
    }
    render() {
        const columns = [
            {
                title: '序号',
                dataIndex: 'index',
                width: 100,
            }, {
                title: '角色名称',
                dataIndex: 'name',
                width: 300,
            },{
                title: '状态',
                dataIndex: 'state',
                width: 80,
                render: (text, record) => <Button
                    style={{background:(record.name==='超级管理员'||record.name==='医生'||record.name==='理疗'||record.name==='前台'||record.name==='药房'||record.name==='收银')&&'#43b1a5',color:(record.name==='超级管理员'||record.name==='医生'||record.name==='理疗'||record.name==='前台'||record.name==='药房'||record.name==='收银')&&'#fff'}}
                    disabled={(record.name==='超级管理员'||record.name==='医生'||record.name==='理疗'||record.name==='前台'||record.name==='药房'||record.name==='收银')?true:false}
                    onClick={this.changeRoleState.bind(this,record)} type={text==='启用'?'primary':'danger'}>
                    {(record.name==='超级管理员'||record.name==='医生'||record.name==='理疗'||record.name==='前台'||record.name==='药房'||record.name==='收银')?'已启用':text=='启用'?'已启用，点击停用':text=='禁用'?'已停用,点击启用':''}
                    </Button>
            },
            {
                title: '权限管理',
                width: 100,
                render: (text, record) => (
                    <div>
                        <Button onClick={this.rolePrivilege.bind(this,record)}  disabled={record.name==='超级管理员'}>权限分配</Button>
                    </div>
                )
            },
            {
                title: '操作',
                width: 200,
                render: (text, record) => (
                    <div>
                        <Button disabled={(record.name==='超级管理员'||record.name==='医生'||record.name==='理疗'||record.name==='前台'||record.name==='药房'||record.name==='收银')?true:false} onClick={this.editRole.bind(this, record)} type="primary" >编辑</Button>
                        <Button disabled={(record.name==='超级管理员'||record.name==='医生'||record.name==='理疗'||record.name==='前台'||record.name==='药房'||record.name==='收银')?true:false} onClick={this.deleteRole.bind(this, record)}  type="danger">删除</Button>
                    </div>
                )
            }
        ];
        let index = this.state.pageindex;
        let size = this.state.pagesize;
        const data = this.state.rolesList.slice(size*(index-1),size*index);
       // console.log(data);
        return (
            <div className='container'>
                <div className='role-manage-box' >
                    {/*添加按钮*/}
                    <div className="storeAdd  ">
                        <Button onClick={() => this.addRole()} type="primary">
                            <img src={require('../../../../images/add.png')} alt=""/>添加角色组</Button>
                    </div>
                    {/* 角色列表 */}
                    <div className='all-roles-table'>
                        <Table
                            rowKey="index"
                            columns={columns}
                            dataSource={data}
                            pagination={false}
                            bordered
                        />
                    </div>
                    <div className="pagination">
                        <Pagination showQuickJumper current={this.state.pageindex} total={this.state.rolesList.length || 1} defaultPageSize={10} onChange={this.changePage.bind(this)} />
                    </div>

                    {/* 新增角色对话框 */}
                    <Modal
                        title={this.state.modalType == 'add' ? '添加' : '编辑'}
                        visible={this.state.visible}
                        onOk={this.handleOk.bind(this)}
                        onCancel={this.handleCancel.bind(this)}
                        className='spgl2-4-1'
                    >
                        {
                            this.state.modalType == 'add' ?
                                <div>
                                    <p className="szma">角色名称<Input placeholder="请输入" value={this.state.addName} onChange={(e) => this.addRoleName(e)} /></p>
                                    <span style={{color:'#f5222d'}}>{this.state.tips1}</span>
                                </div>
                                :
                                <div>
                                    <p className="szma">原角色名称<Input readOnly value={this.state.role.name} /></p>
                                    <p className="szma">新角色名称<Input placeholder="请输入" value={this.state.editName} onChange={(e) => this.editRoleName(e)} /></p>
                                    <span style={{color:'#f5222d'}}>{this.state.tips}</span>
                                </div>
                        }
                    </Modal>
                </div>
            </div>
        )
    }
}
